import type { FormInstance } from 'element-plus'
import type { aliMapAddressTypes } from '../map/typings'
import type { PowerDistributionFacilitiesDataItemType } from '../../facilityManagement/powerDistributionFacilities/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { uniqWith } from 'lodash'
import { ElRow, ElCol, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElLink } from 'element-plus'
import AliIcon from '~/components/AliIocn'
import MapView from '../map/MapView'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'MapLocation',
  props: ['detail'],
  setup(props, { expose }) {
    const mapViewRef = ref()
    const ruleFormRef = ref<FormInstance>()
    const selectAddressRef = ref<string>()
    const selectAddressSearchRef = ref<string>()
    const selectAddressOptionsRef = ref<aliMapAddressTypes[]>([])
    const markerPosition = ref<{ lat: number; lng: number }>()
    const formValues = reactive<PowerDistributionFacilitiesDataItemType>(
      props?.detail
        ? {
            id: props.detail?.id,
            address: props.detail?.address,
            addressCoordinates: props.detail?.lat && `${props.detail?.lon},${props.detail?.lat}`
          }
        : {}
    )
    const userState = useVuexGetters('user', ['userAddressInfo'])

    // 切换地址选择回调
    const handleChangeAddressSelect = (value: string) => {
      formValues.addressCoordinates = value
      // 再去匹配对应的值并获取对应的设施地址
      formValues.address = selectAddressOptionsRef.value?.find(
        (item) => `${item?.location?.lng},${item?.location?.lat}` === value
      )?.address
      // 更新地图标记点位置
      markerPosition.value = value?.includes(',')
        ? {
            lng: parseFloat(formValues.addressCoordinates?.split(',')[0]!),
            lat: parseFloat(formValues.addressCoordinates?.split(',')[1]!)
          }
        : undefined
      if (!mapViewRef.value.mapState.currentMarker) {
        const timer = setTimeout(() => {
          mapViewRef.value.setMarkersByPropsMarkers()
          clearTimeout(timer)
        }, 0)
      }
    }

    // 修改经纬度回调
    const handleChangeAddressCoordinates = (value: string) => {
      selectAddressRef.value = undefined
      formValues.address = undefined
      markerPosition.value = value?.includes(',')
        ? {
            lng: parseFloat(formValues.addressCoordinates?.split(',')[0]!),
            lat: parseFloat(formValues.addressCoordinates?.split(',')[1]!)
          }
        : undefined

      if (!markerPosition.value) mapViewRef.value.clearCurrentMarker()
      // formValues.addressCoordinates?.includes(',')
      //       ? {
      //           lat: formValues.addressCoordinates?.split(',')[0],
      //           lng: formValues.addressCoordinates?.split(',')[1]
      //         }
      //       : undefined
    }

    // 地图点更换后的回调
    // const handleChangeSelectAddressOptions = (list: aliMapAddressTypes[]) => {
    // selectAddressOptionsRef.value = list
    // selectAddressRef.value = undefined
    // formValues.facilityAddress = undefined
    // formValues.addressCoordinates = undefined
    // }

    // 地图点更换位置后的回调
    const handleSetAddressInfo = (address: string, lngLat: [number, number]) => {
      formValues.address = address
      formValues.addressCoordinates = lngLat.join(',')
    }

    // 地址选择下拉框输入停止后回调
    const handleFilterAddressSearch = (value: string) => {
      selectAddressSearchRef.value = handleTrim(value)
      // if (selectAddressSearchRef.value && selectAddressOptionsRef.value?.length) {
      //   selectAddressOptionsRef.value = selectAddressOptionsRef.value.filter(item => item.name?.includes(selectAddressSearchRef.value!))
      // }
      handleSearchAddressSelectList()
    }

    // 点击地图左上角查询按钮的时候回调 | 在
    const handleSearchAddressSelectList = (e?: Event) => {
      if (e) e.stopPropagation()
      const placeSearch = new mapViewRef.value.aMapRef.PlaceSearch({
        city: userState.userAddressInfo.value.city,
        citylimit: false
      }) // 构造地点查询类
      placeSearch.search(
        selectAddressSearchRef.value,
        (status: string, result: Record<string, any>) => {
          selectAddressOptionsRef.value =
            status === 'complete' && result.info === 'OK'
              ? uniqWith(
                  result.poiList.pois,
                  (item: { name: string }, nextItem: { name: string }) =>
                    item.name === nextItem.name
                )
              : []
        }
      )
    }

    onMounted(() => {
      if (props.detail?.lat)
        markerPosition.value = {
          lng: props.detail?.lon,
          lat: props.detail?.lat
        }
    })

    expose({ ruleFormRef, formValues })

    return () => (
      <>
        <MapView
          id={styles['map-location-amap']}
          ref={mapViewRef}
          clickon
          marker={markerPosition.value}
          onSetAddressInfo={handleSetAddressInfo}
          // onSelectAddressList={handleChangeSelectAddressOptions}
        />
        <ElFormItem class={styles['map-location-select-address']}>
          <ElSelect
            v-model={selectAddressRef.value}
            filterable
            suffixIcon={<AliIcon type="icon-sousuo" />}
            remote
            defaultFirstOption
            clearable
            placeholder="请输入地址"
            remoteMethod={handleFilterAddressSearch}
            onChange={handleChangeAddressSelect}
          >
            {selectAddressOptionsRef.value?.map((item) => (
              <ElOption
                class={styles['map-location-option-address']}
                key={item?.id}
                label={item?.name}
                value={`${item?.location?.lng},${item?.location?.lat}`}
              >
                <ElLink underline={false} type="info">
                  <AliIcon type="icon-ditudingwei" />
                </ElLink>
                <section class="option-text">
                  <b>{item?.name}</b>
                  <p>{item?.address}</p>
                </section>
              </ElOption>
            ))}
          </ElSelect>
        </ElFormItem>
        <ElForm ref={ruleFormRef} model={formValues} labelWidth={100} labelPosition="right">
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem
                prop="address"
                label="设施地址"
                rules={[{ required: false, message: '请选择设施地址' }]}
              >
                <ElInput
                  readonly
                  v-model={formValues.address}
                  suffixIcon={<AliIcon type="icon-dingwei" />}
                  {...{ maxlength: 50 }}
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem
                prop="addressCoordinates"
                label="地址坐标"
                rules={[{ required: true, message: '请选择地址坐标' }]}
              >
                <ElInput
                  v-model={formValues.addressCoordinates}
                  {...{ maxlength: 50 }}
                  onChange={handleChangeAddressCoordinates}
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </>
    )
  }
})
